package com.ls.fw.data.bean;

import java.util.ArrayList;
import java.util.List;

/**
 * Mybatis - 分页对象
 *
 */
public class PageList<E> extends ArrayList<E> {
    private static final long serialVersionUID = 1L;

    /**页码，从1开始*/
    private int page = 1;
    /**页面大小*/
    private int pageSize;
    /**起始行*/
    private int startRow = 1;
    /**末行*/
    private int endRow = 1;
    /**总数*/
    private long allRow;
    /**总页数*/
    private int totalPage;

	private boolean reasonable = true; 

    public PageList(){
    	super();
    }

    public PageList(int page, int pageSize) {
        super(pageSize > -1 ? pageSize : 0);
        this.page = page;
        this.pageSize = pageSize;
        calculateStartAndEndRow();
    }

    public List<E> getResult() {
        return this;
    }

    public int getEndRow() {
        return endRow;
    }

    public void setPage(int page) {
        //分页合理化，针对不合理的页码自动处理
        this.page = (page <= 0) ? 1 : page;
    }

    public int getPageListSize() {
        return pageSize;
    }

    public void setPageListSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getStartRow() {
        return startRow;
    }


    public void setReasonable(boolean reasonable) {
        this.reasonable = reasonable;
        //分页合理化，针对不合理的页码自动处理
        if (this.reasonable && this.page <= 0) {
            this.page = 1;
            calculateStartAndEndRow();
        }
    }

    /**
     * 计算起止行号
     */
    private void calculateStartAndEndRow() {
        this.startRow = this.page > 1 ? (this.page - 1) * this.pageSize : 1;
        int step = this.pageSize * (this.page > 0 ? 1 : 0);
        this.endRow = this.startRow + (step>0?step-1:step);
    }



	public int getPageSize() {
		return this.pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getPage() {
		return this.page;
	}

	public boolean isReasonable() {
		return this.reasonable;
	}

	public void setStartRow(int startRow) {
		this.startRow = startRow;
	}

	public void setEndRow(int endRow) {
		this.endRow = endRow;
	}

	public long getAllRow() {
		return allRow;
	}

	public void setAllRow(long allRow) {
		this.allRow = allRow;
	   if (pageSize > 0) {
            totalPage = (int) (allRow / pageSize + ((allRow % pageSize == 0) ? 0 : 1));
        } else {
            totalPage = 0;
        }
        //分页合理化，针对不合理的页码自动处理
        if (page > totalPage) {
            page = totalPage;
            calculateStartAndEndRow();
        }
	}

	public int getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	@Override
	public String toString() {
		return "page=" + this.page + ", pageSize=" + this.pageSize
				+ ", startRow=" + this.startRow + ", endRow=" + this.endRow
				+ ", allRow=" + this.allRow + ", totalPage=" + this.totalPage
				+ ", reasonable=" + this.reasonable + ","+super.toString() ;
	}
}
